package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import common.VSM_NetWrapper;
import common.VSM_WrapperAcknowledgment;
import common.VSM_WrapperConnect;
import common.VSM_WrapperData;
import common.VSM_WrapperDisconnect;

public class VSM_ClientHandler extends Thread
{
	private final Socket myClientSocket;
	private VSM_Monitor fatherWindow;
	private VSM_DataDisplay myClientDisplay;
	
	public VSM_ClientHandler(Socket clientSocket,VSM_Monitor parent)
	{
		this.myClientSocket = clientSocket;
		this.fatherWindow = parent;
		
		start();
	}
	
	@Override
	public void run()
	{		
		try
		{
			ObjectOutputStream toClient = new ObjectOutputStream(myClientSocket.getOutputStream());
			ObjectInputStream fromClient = new ObjectInputStream(myClientSocket.getInputStream());
			VSM_NetWrapper wrapper;
			VSM_WrapperAcknowledgment acknowledgment;
			
			VSM_WrapperConnect connect = null;
			
			wrapper = (VSM_NetWrapper)fromClient.readObject();
			
			if(wrapper instanceof VSM_WrapperConnect)
			{
				connect = (VSM_WrapperConnect)wrapper;
				myClientDisplay = new VSM_DataDisplay(connect.getSensorID(), connect.getSensorUnit(), connect.getBottomValue(), connect.getTopValue(), connect.getTimeOut());
				
				acknowledgment = new VSM_WrapperAcknowledgment(myClientSocket.getLocalAddress().toString(), myClientSocket.getLocalPort(),connect.getSensorID());
				toClient.writeObject(acknowledgment);
			}
			
			while(true)
			{
				VSM_WrapperData data;
				
				wrapper = (VSM_NetWrapper)fromClient.readObject();
				
				if(wrapper instanceof VSM_WrapperData)
				{
					data = (VSM_WrapperData)wrapper;
					
					acknowledgment = new VSM_WrapperAcknowledgment(myClientSocket.getLocalAddress().toString(), myClientSocket.getLocalPort(),connect.getSensorID());
					toClient.writeObject(acknowledgment);
				}
				
				else if(wrapper instanceof VSM_WrapperDisconnect)
				{
					acknowledgment = new VSM_WrapperAcknowledgment(myClientSocket.getLocalAddress().toString(), myClientSocket.getLocalPort(),connect.getSensorID());
					toClient.writeObject(acknowledgment);
					myClientSocket.close();
					break;
				}
			}
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(myClientSocket != null)
				myClientSocket.close();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
		
	}
}
